package com.changgou.filter;

import com.changgou.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author tang.qingbo
 * @Date 2020/9/1 20:27
 * @Version 1.0
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    /**
     * 定义令牌头部信息
     */
    private static final String AUTHORIZE_TOKEN = "Authorization";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request,response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取当前请求路径
        String loginPath = request.getURI().getPath();
        if ("/api/user/login".equals(loginPath)) {
            //登录请求==直接放行
            return chain.filter(exchange);
        }

        //获取请求头中的token
        String token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);
        if (StringUtils.isEmpty(token)) {
            //从请求参数中获取token信息
            token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
        }

        //判断是否为空,从cookie中获取
        if (StringUtils.isEmpty(token)) {
            HttpCookie cookie = request.getCookies().getFirst(AUTHORIZE_TOKEN);
            if (cookie == null) {
                //为空,不允许访问,设置响应状态码为 401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                //返回结果
                return response.setComplete();
            }

            //否者获取cookie的值==就是保存的token
            token = cookie.getValue();

            //放入请求头中
            request.mutate().header(AUTHORIZE_TOKEN, "bearer "+token);

        }

        //放行
        return chain.filter(exchange);
    }

    /**
     * 返回值代表过滤器的执行顺序,值越小,优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
